package com.google.gaedlab;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class QrCodeServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String url = req.getRequestURL().toString();
		url = url.substring(url.lastIndexOf("/") + 1);
		int pos = url.lastIndexOf("?");
		if (pos > 0) {
			url = url.substring(0, pos);
		}
		pos = url.lastIndexOf(".");
		if (pos > 0) {
			url = url.substring(0, pos);
		}
		String name = url;
		if ("".equals(name) || "index".equals(name) || "qr".equals(name)) {
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else if ("edit".equals(name)) {
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else if ("show".equals(name)) {
			Entity e = QrService.find(req.getParameter("id"));
			req.setAttribute("qrEntity", e);
			req.setAttribute("qrShow", true);
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else if ("showText".equals(name)) {
			Entity e = QrService.find(req.getParameter("id"));
			resp.setContentType("text/plain");
			resp.getWriter().print(e == null ? "" : ((Text) e.getProperty("text")).getValue());
		} else if ("create".equals(name)) {
			Entity e = QrService.add(req.getParameter("text"));
			req.setAttribute("qrEntity", e);
			req.setAttribute("qrShow", true);
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else {
			System.out.println("no such method: " + name);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}

}
